package com.example.myapplication2;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.display.DisplayManager;
import android.media.MediaRouter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Toast;
import android.Manifest;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final int PICK_IMAGE_REQUEST = 200;
    private static final int PERMISSION_REQUEST_CODE = 300;
    private final String TAG = "MainActivity_log";
    private MyPresentation myPresentation;
    private Uri selectedImageUri;

    // 在 MainActivity 类中添加
    private ActivityResultLauncher<Intent> imagePickerLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermission();
        // 在 onCreate() 中初始化
        imagePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        Uri uri = result.getData().getData();
                        displayImageOnSecondaryScreen(uri);
                    }
                }
        );

        findViewById(R.id.show_presentation).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPresentation();
            }
        });

        findViewById(R.id.close_presentation).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePresentation();
            }
        });
        //权限检查
//        findViewById(R.id.btn_select_image).setOnClickListener(v -> {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//                // Android 13+ 需要 READ_MEDIA_IMAGES
//                if (checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
//                    requestPermissions(new String[]{Manifest.permission.READ_MEDIA_IMAGES}, PERMISSION_REQUEST_CODE);
//                } else {
//                    openGallery();
//                }
//            } else {
//                // Android 12- 需要 READ_EXTERNAL_STORAGE
//                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
//                } else {
//                    openGallery();
//                }
//            }
//            //displayDrawableResource();
//        });

        // 修改按钮点击监听
        findViewById(R.id.btn_select_image).setOnClickListener(v -> checkAndOpenGallery());
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //SYSTEM_ALERT_WINDOW权限申请
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, 100);
            } else {
                Log.d(TAG, "Permission gained.");
            }
        }
    }

    // 统一权限检查逻辑
    private void checkAndOpenGallery() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_MEDIA_IMAGES}, PERMISSION_REQUEST_CODE);
                return;
            }
        } else {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
                return;
            }
        }

        openGallery();  // 权限通过后启动选择器
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    //已获得权限
                    Toast.makeText(MainActivity.this, "Permission gained.", Toast.LENGTH_SHORT).show();
                } else {
                    //未获取到权限
                    Toast.makeText(MainActivity.this, "Permission denied!", Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
            if (data != null && data.getData() != null) {
                selectedImageUri = data.getData();
                displayImageOnSecondaryScreen(selectedImageUri);
            } else {
                Toast.makeText(this, "未选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //显示副屏
    private void showPresentation() {
        //方式1
//        MediaRouter mediaRouter = (MediaRouter) getSystemService(Context.MEDIA_ROUTER_SERVICE);
//        MediaRouter.RouteInfo route = mediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_AUDIO);
//        if (route != null) {
//            Display presentationDisplay = route.getPresentationDisplay();
//            if (presentationDisplay != null) {
//                myPresentation = new MyPresentation(MainActivity.this, presentationDisplay);
//                myPresentation.show();
//            }
//        } else {
//            Toast.makeText(MainActivity.this, "不支持分屏", Toast.LENGTH_SHORT).show();
//        }

        //方式2
       DisplayManager mDisplayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        Display[] displays = mDisplayManager.getDisplays();
        if (displays.length > 1) {
            //displays[0] 主屏，displays[1] 副屏
            myPresentation = new MyPresentation(MainActivity.this, displays[1]);
            myPresentation.show();
        } else {
            Toast.makeText(MainActivity.this, "不支持分屏", Toast.LENGTH_SHORT).show();
        }

        displayDrawableResource();
    }

    //关闭副屏
    private void closePresentation() {
        if (myPresentation != null) {
            myPresentation.dismiss();
            myPresentation = null;
        }
    }

    private void openGallery() {
        Intent pick = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                .setType("image/*")
                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        try {
            imagePickerLauncher.launch(pick);
        } catch (ActivityNotFoundException e) {
            // 兜底：使用更通用的 GET_CONTENT
            Intent getContent = new Intent(Intent.ACTION_GET_CONTENT)
                    .setType("image/*")
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imagePickerLauncher.launch(
                    Intent.createChooser(getContent, "请选择图片"));
        }
    }

    // 新增方法：显示本地 drawable 资源
    private void displayDrawableResource(){
        int drawableResId = R.drawable.www002;
        displayImageOnSecondaryScreen(drawableResId);
    }

    // 新增方法：统一处理图片显示逻辑
    private void displayImageOnSecondaryScreen(Object imageSource) {
        if (myPresentation == null){
            showPresentation();
        }

        if (imageSource instanceof Integer) {
            // 显示 drawable 资源
            myPresentation.setImageResource((Integer) imageSource);
        } else if (imageSource instanceof Uri) {
            // 显示相册图片
            myPresentation.setImageUri((Uri) imageSource);
        }

    }
}
